<script setup lang="ts">
import { ElScrollbar, ElMessageBox, ElMessage } from 'element-plus'
import { propTypes } from '@/utils/propTypes'
import { reactive, watch, onMounted, nextTick, ref } from 'vue'
import { Paging, CListEventPrefix } from '@/config/public'
import { useI18n } from '@/hooks/web/useI18n'
import { getDataOfTable } from '@/api/develop/list'
import {
  getStyles,
  filterTableColumns,
  canSearchByKey,
  formatData,
  getDataTypeAbbr
} from '../DataRender'
import { delFormData, batchDelFormData } from '@/api/develop/form'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { useAppStore } from '@/store/modules/app'
import { useEmitt } from '@/hooks/web/useEmitt'
import { deepClone } from '@/utils'
import { useRouter } from 'vue-router'

const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const appStore = useAppStore()
const { t } = useI18n()
const { push, currentRoute } = useRouter()

defineOptions({
  name: 'DataTableView'
})
const tableRef = ref()

const props = defineProps({
  listDef: propTypes.object,
  preview: propTypes.bool
})

const initCondFields = ['', '', '', '', '', '', '', '', '']
const initCondOprs = ['EQ', 'EQ', 'EQ', 'EQ', 'EQ', 'EQ', 'EQ', 'EQ', 'EQ']
const initCondValues = ['', '', '', '', '', '', '', '', '']
const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{} as any],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: Paging.defaultSize,
    params: {},
    listId: '',
    sortField: '',
    sortOrder: ''
  },
  colHeaderName: '',
  listTitle: '',
  filterFields: [{} as any],
  condFields: initCondFields,
  condOprs: initCondOprs,
  condValues: initCondValues,
  highLevelSearch: false,
  canSearchByKey: false,
  canMutiSelect: false,
  showSerialNo: true,
  readOnly: false,
  curFormId: '',
  seletedIds: '',
  tableColumns: [{} as any]
})

onMounted(() => {
  let listNameField = 'name'
  state.colHeaderName = 'headerText'
  if (curLang == 'en') {
    state.colHeaderName = 'headerEn'
    listNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.colHeaderName = 'headerHk'
    listNameField = 'hkName'
  }
  state.tableView = []
  state.listTitle = props.listDef[listNameField]
})

//监控实体ID的变化
watch(
  () => props.listDef,
  async (val: any) => {
    state.readOnly = true
    state.canMutiSelect = false
    state.showSerialNo = true
    if (!val && val.id) {
      state.tableView = []
      state.curFormId = ''
      return
    }
    await nextTick()
    state.canSearchByKey = canSearchByKey(props.listDef.cols)
    state.filterFields = props.listDef.cols.filter((col) => col.isFilter == 1)
    state.filterFields.push({
      id: '',
      headerText: '请选择',
      enName: 'Please Select',
      headerHk: '請選擇',
      fieldName: ''
    })
    state.queryBody.listId = val.id
    state.queryBody.pageSize = val.pageSize
    state.tableColumns = filterTableColumns(props.listDef.cols)
    state.canMutiSelect = props.listDef.canSelectMore == 1
    state.showSerialNo = props.listDef.showSerialNo == 1
    if (props.listDef.pcFormId) {
      state.curFormId = props.listDef.pcFormId
      state.readOnly = false
    } else {
      state.curFormId = props.listDef.pcFormReadId
    }
    if (props.listDef.isLazy != 1) {
      handleSearch()
    }
  },
  {
    immediate: true
  }
)

const changePage = (page) => {
  state.queryBody.pageNo = page
  handleSearch()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  handleSearch()
}

// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  queryData()
}
//重置查询
const resetSearch = () => {
  state.searchKey = ''
  state.queryBody.params = {}
  for (let i = 0; i < 9; i++) {
    state.condFields[i] = ''
    state.condValues[i] = ''
    state.condOprs[i] = 'EQ'
  }
  handleSearch()
}

//查询数据
const queryData = async () => {
  appStore.setFooter(false)
  state.tableView = []
  let queryBody = deepClone(state.queryBody) as any
  for (let i = 0; i < 9; i++) {
    if (state.condFields[i]) {
      queryBody.params['Q_' + state.condFields[i] + '_' + state.condOprs[i]] = state.condValues[i]
    }
  }
  queryBody.language = curLang
  await getDataOfTable(queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      state.tableView = data
      state.totalCount = result.result.totalCount
    })
    .catch(() => {})
}

//双击行,直接查看明细
const dblclickRow = (row) => {
  edit(row.pkId)
}

//编辑记录
const edit = (id) => {
  push({
    name: 'FormShow',
    query: {
      pkId: id,
      formId: state.curFormId,
      readonly: props.preview || state.readOnly ? 1 : 0,
      preview: props.preview ? 1 : 0,
      fromPath: currentRoute.value.fullPath
    }
  })
}

//表格选中行事件
const handleSelectionChange = (rows) => {
  if (rows.length == 0) {
    state.seletedIds = ''
    return
  }
  let ids = rows.map((row) => row.pkId).join(',')
  state.seletedIds = ids
}

// 批量删除选中的记录
const batchDelete = () => {
  const ids = state.seletedIds
  if (ids == null || ids.length == 0) {
    ElMessage.warning(t('common.selectAny'))
    return
  }
  ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await batchDelFormData(ids, state.curFormId)
      handleSearch()
    })
    .catch(() => {})
}

// 刪除当前记录
const deleteOne = (id) => {
  ElMessageBox.confirm(t('form.deleteTip'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delFormData(id, state.curFormId)
      handleSearch()
    })
    .catch(() => {})
}

/**
 * @description  定义自定义列表刷新事件
 */
useEmitt({
  //刷新列表事件
  name: CListEventPrefix + props.listDef.id,
  callback: (type: string) => {
    if (type === 'add') {
      state.queryBody.pageNo = 1
    }
    handleSearch()
  }
})
</script>

<template>
  <ElScrollbar style="margin: -18px -8px">
    <div>
      <!-- 搜索條件卡片 -->
      <el-card>
        <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
          <el-col :sm="6" :md="4" style="text-align: left; font-size: 12px; font-weight: bold">
            {{ state.listTitle }}
          </el-col>
          <el-col
            :sm="6"
            :md="4"
            style="text-align: right; font-size: 12px"
            v-if="state.canSearchByKey"
          >
            {{ $t('dataList.searchKey') }}</el-col
          >
          <el-col :sm="12" :md="4" style="text-align: left" v-if="state.canSearchByKey">
            <el-input
              v-model="state.searchKey"
              @keyup.enter="handleSearch"
              :placeholder="$t('dataList.searchTip')"
            />
          </el-col>
          <el-col :sm="24" :md="12" style="text-align: right">
            <div style="margin-right: -5px">
              <el-button @click="handleSearch" type="primary" size="small" plain
                ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span>
              </el-button>
              <el-button
                @click="state.highLevelSearch = !state.highLevelSearch"
                type="info"
                size="small"
                plain
                ><Icon icon="mdi:filter-plus" /><span>{{ $t('dataList.highLevel') }}</span>
              </el-button>
              <el-button @click="resetSearch" type="info" size="small" plain>
                <Icon icon="icon-park-solid:clear-format" /><span>{{ $t('common.reset') }}</span>
              </el-button>
              <el-button
                type="danger"
                size="small"
                plain
                @click="batchDelete()"
                v-if="!state.readOnly && state.canMutiSelect"
              >
                <Icon icon="fluent:delete-lines-20-filled" /><span>{{
                  $t('dataList.batchDel')
                }}</span>
              </el-button>
              <el-button
                type="success"
                size="small"
                plain
                @click="edit(null)"
                v-if="!state.readOnly"
              >
                <Icon icon="material-symbols:add-circle-rounded" /><span>{{
                  $t('common.add')
                }}</span>
              </el-button>
            </div>
          </el-col>
        </el-row>
        <el-row v-show="state.highLevelSearch" :gutter="20">
          <!-- 高级查询条件-->
          <el-col :sm="24" :md="8" v-for="index in 9" :key="index">
            <el-select
              v-model="state.condFields[index - 1]"
              :placeholder="$t('common.selectText')"
              size="default"
              class="condField"
            >
              <el-option
                v-for="item in state.filterFields"
                :key="item.id"
                :label="item[state.colHeaderName]"
                :value="
                  (item.tableAlias ? item.tableAlias + '.' : '') +
                  item.fieldName +
                  '_' +
                  getDataTypeAbbr(item.colType)
                "
              />
            </el-select>
            <el-select
              v-model="state.condOprs[index - 1]"
              :placeholder="$t('common.selectText')"
              size="default"
              class="condOp"
            >
              <el-option value="EQ" :label="$t('dataList.EQ')" />
              <el-option value="NEQ" :label="$t('dataList.NEQ')" />
              <el-option
                value="GT"
                :label="$t('dataList.GT')"
                v-if="!state.condFields[index - 1].endsWith('_S')"
              />
              <el-option
                value="GE"
                :label="$t('dataList.GE')"
                v-if="!state.condFields[index - 1].endsWith('_S')"
              />
              <el-option
                value="LT"
                :label="$t('dataList.LT')"
                v-if="!state.condFields[index - 1].endsWith('_S')"
              />
              <el-option
                value="LE"
                :label="$t('dataList.LE')"
                v-if="!state.condFields[index - 1].endsWith('_S')"
              />
              <el-option
                value="LK"
                :label="$t('dataList.LK')"
                v-if="state.condFields[index - 1].endsWith('_S')"
              />
              <el-option
                value="LEK"
                :label="$t('dataList.LEK')"
                v-if="state.condFields[index - 1].endsWith('_S')"
              />
              <el-option
                value="RIK"
                :label="$t('dataList.RIK')"
                v-if="state.condFields[index - 1].endsWith('_S')"
              />
              <el-option value="ISNULL" :label="$t('dataList.ISNULL')" />
              <el-option value="NOTNULL" :label="$t('dataList.NOTNULL')" />
              <el-option value="IN" :label="$t('dataList.IN')" />
            </el-select>
            <el-input v-model="state.condValues[index - 1]" class="condValue" />
          </el-col>
        </el-row>
      </el-card>
      <el-container class="mainArea">
        <el-main class="formcard">
          <!-- 搜索結果表格 -->
          <el-table
            :data="state.tableView"
            ref="tableRef"
            tooltip-effect="light"
            style="width: 100%; border: 1px solid #ddd; font-size: 12px"
            stripe
            row-key="pkId"
            default-expand-all
            highlight-current-row
            @row-dblclick="dblclickRow"
            @selection-change="handleSelectionChange"
            :header-cell-style="{
              background: 'var(--el-color-primary-light-9)',
              color: '#409eff'
            }"
          >
            <el-table-column type="selection" width="38" v-if="state.canMutiSelect" />
            <el-table-column type="index" min-width="60" v-if="state.showSerialNo">
              <template #header>
                <div style="margin-bottom: -10px">
                  <Icon
                    icon="ant-design:field-number-outlined"
                    size="24"
                    :title="$t('common.number')"
                /></div>
              </template>
            </el-table-column>
            <!--动态渲染列-->
            <el-table-column
              :prop="col.fieldName"
              :label="col[state.colHeaderName]"
              :width="col.colWidth"
              :align="col.textAlign == 1 ? 'center' : col.textAlign == 2 ? 'right' : 'left'"
              :key="col.fieldName"
              v-for="col in state.tableColumns"
            >
              <template #default="{ row }">
                <div v-if="col.isLink" :style="getStyles(col)">
                  <a :href="col.linkUrl" target="_blank" style="color: blue">
                    {{ formatData(row[col.fieldAlias ? col.fieldAlias : col.fieldName], col) }}</a
                  >
                </div>
                <div v-else :style="getStyles(col)">
                  {{ formatData(row[col.fieldAlias ? col.fieldAlias : col.fieldName], col) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('common.operation')"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  type="primary"
                  plain
                  circle
                  size="small"
                  :title="state.readOnly ? $t('common.check') : $t('common.modify')"
                  @click="edit(row.pkId)"
                >
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
                <el-button
                  type="danger"
                  plain
                  circle
                  size="small"
                  :title="$t('common.delete')"
                  v-if="!state.readOnly"
                  @click="deleteOne(row.pkId)"
                >
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分頁器 -->
          <div class="demo-pagination-block"
            ><el-pagination
              v-model:currentPage="state.queryBody.pageNo"
              v-model:page-size="state.queryBody.pageSize"
              @current-change="changePage"
              @size-change="changePageSize"
              :page-sizes="state.pageSizes"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.totalCount"
              style="font-size: 12px !important"
          /></div>
        </el-main>
      </el-container>
    </div>
  </ElScrollbar>
</template>

<style lang="less" scoped>
.condField {
  width: 40%;
}
.condOp {
  width: 28%;
}
.condValue {
  width: 28%;
}
.is-hover {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 10px 50px;
}
:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  overflow-x: hidden;
  height: 420px;
}
.formcard {
  margin: -12px -19px 0 -15px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(span.el-pagination__jump) {
  font-size: 12px;
}
:deep(span.el-pagination__total) {
  font-size: 12px;
}
:deep(.btn-next) {
  height: 28px;
}
:deep(.el-pagination button) {
  height: 28px;
}
</style>
